/**
 * @license
 * Copyright 2021 KonghaYao 江夏尧 <dongzhongzhidong@qq.com>
 * SPDX-License-Identifier: Apache-2.0
 */

const config = { proxy: null, silent: false };
let realFetch;

// 假的 Response 对象
import fakeResponse from './src/response.js';
function injectDefaultOptions(options, other) {
    return { method: 'GET', body: null, headers: new Headers(), ...options, ...other };
}

async function fakeFetch(url, options = {}) {
    // 只有在 $mock 标记为 true 时才进行代理
    if (window.fetch.$mock === true) {
        // ! 传入初始参数
        const RequestPackage = injectDefaultOptions(options, {
            url: url instanceof URL ? url : new URL(url, window.location.origin),
        });

        const result = await config.proxy(RequestPackage);
        if (result) {
            if (!config.silent) console.warn('fetch: mock代理中', url);
            const { body, headers, status } = result;
            return new fakeResponse(body, { headers, status, url });
        }
        // 这里穿透下去
    }
    if (!config.silent) console.warn('这次 fetch 未使用 mockjs');
    return realFetch(url, options);
}

// 代理出口
export function mockFetch({ proxy, silent = false }) {
    if (proxy instanceof Function) config.proxy = proxy;
    config.silent = silent;

    if (window.fetch && !window.fetch.$mock) {
        [realFetch, window.fetch] = [window.fetch, fakeFetch];
        window.fetch.$mock = true;
        if (!silent) console.warn('fetch: 已经被代理');
    }
}
